import 'dart:convert';

//import 'package:device_verify/device_verify.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_oh_test/pages/sub_web_page.dart';
import 'package:flutter_share/flutter_share.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'package:location/location.dart';
import 'package:location/types.dart';
import 'package:share_extend/share_extend.dart';

//import 'package:image_gallery_saver/image_gallery_saver.dart';
//import 'package:permission_handler/permission_handler.dart';

import 'pages/PaymentResult.dart';

class OhosAbilityPage extends StatefulWidget {
  const OhosAbilityPage({super.key, required this.title});

  final String title;

  @override
  State<OhosAbilityPage> createState() => _OhosAbilityPageState();
}

class _OhosAbilityPageState extends State<OhosAbilityPage> {
  final GlobalKey _globalKey = GlobalKey();
  String msg = "init";
  final Location location = Location();
  final FlutterShare _flutterShare = FlutterShare();
  bool _loading = false;
  GeoAddress? _location;
  String? _error;
  final ImagePicker _picker = ImagePicker();

  //PermissionStatus _permissionStatus = PermissionStatus.denied;
  final MethodChannel _channel = MethodChannel('plugins.flutter.io/call_ohos');
  var contextRef;

  //final _deviceVerifyPlugin = DeviceVerify();

  @override
  Widget build(BuildContext context) {
    contextRef = context;
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            children: [
              Text(
                msg,
                style: Theme.of(context).textTheme.headlineMedium,
              ),
              Text(
                'Location: ${_error ?? _location?.locality ?? "unknown"}',
                style: Theme.of(context).textTheme.bodyLarge,
              ),
              Expanded(child: buildButtonGrid()),
              /* RepaintBoundary(
                key: _globalKey,
                child: Container(
                  height: 200,
                  padding: const EdgeInsets.all(10),
                  child: Image.asset("assets/images/bg.png"),
                ),
              ),*/
            ],
          ),
        ));
  }

  Widget buildButtonGrid() {
    return GridView.count(
        padding: const EdgeInsets.all(10),
        //一列排布的组件的个数
        crossAxisCount: 2,
        //水平子 Widget 之间的间距
        crossAxisSpacing: 5.0,
        //垂直子 Widget 之间的间距
        mainAxisSpacing: 5.0,
        // 宽高比
        childAspectRatio: 4,
        children: [
          ElevatedButton(
            onPressed: () {
              //getDeviceToken();
            },
            child: const Text("getDeviceToken"),
          ),
          ElevatedButton(
            onPressed: () {
              scanCode();
            },
            child: const Text("扫码"),
          ),
          ElevatedButton(
            onPressed: () {
              aliPay();
            },
            child: const Text("支付宝"),
          ),
          ElevatedButton(
            onPressed: () {
              wechatPay();
            },
            child: const Text("微信支付"),
          ),
          ElevatedButton(
            onPressed: () {
              shareText();
            },
            child: const Text("微信分享"),
          ),
          ElevatedButton(
            onPressed: () {
              selectImages(null);
            },
            child: const Text("打开图库"),
          ),
          ElevatedButton(
            onPressed: () {
              selectContracts("444");
            },
            child: const Text("打开联系人"),
          ),
          ElevatedButton(
            onPressed: () {
              startAppGallery();
            },
            child: const Text("打开应用市场"),
          ),
          ElevatedButton(
            onPressed: () {
              _saveLocalImage();
            },
            child: const Text("保存图片"),
          ),
          ElevatedButton(
            onPressed: () {
              requestPermission();
            },
            child: const Text("申请位置权限"),
          ),
          ElevatedButton(
            onPressed: () {
              getPosition("");
            },
            child: const Text("获取当前位置"),
          ),
          ElevatedButton(
            onPressed: () {
              gotoSubWebPage("https://m.hnair.com/#/user/pwdback1?_k=uplsg5");
            },
            child: const Text("打开子页面"),
          ),
          ElevatedButton(
            onPressed: () {
              quickLogin();
            },
            child: const Text("一键登录"),
          ),
          ElevatedButton(
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.white70),
                foregroundColor: MaterialStateProperty.all(Colors.black)),
            onPressed: () {
              ShareExtend.share("share text", "text",
                  sharePanelTitle: "share text title",
                  subject: "share text subject");
            },
            child: Text("share text"),
          ),
          ElevatedButton(
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.white70),
                foregroundColor: MaterialStateProperty.all(Colors.black)),
            onPressed: () async {
              final XFile? pickedFile = await _picker.getImage();
              if (pickedFile != null) {
                ShareExtend.share(pickedFile.path, "image",
                    sharePanelTitle: "share image title",
                    subject: "share image subject");
              }
            },
            child: Text("share image"),
          ),
        ]);
  }

  /*Future<void> getDeviceToken() async {
    String deviceToken;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      deviceToken = await _deviceVerifyPlugin.getDeviceToken() ?? 'Unknown platform version';
      setState(() {
        _counter = deviceToken;
      });
    } on PlatformException {
      deviceToken = 'Failed to getDeviceToken.';
    }
  }*/

  //获取定位
  Future<void> getPosition(dynamic arguments) async {
    /*String result =
        (await _channel.invokeMethod<String>('getPosition', arguments)) ??
            "xxx";
    setState(() {
      msg = result;
    });*/
    setState(() {
      _error = null;
      _loading = true;
    });
    try {
      final locationResult = await location.getGeoAddress();

      setState(() {
        _location = locationResult;
        _loading = false;
      });
    } on PlatformException catch (err) {
      setState(() {
        _error = err.code;
        _loading = false;
      });
    }
  }

  //选择联系人
  Future<void> selectContracts(dynamic arguments) async {
    String result =
        (await _channel.invokeMethod<String>('selectContracts', arguments)) ??
            "xxx";
    setState(() {
      msg = result;
    });
  }

  //扫码
  Future<void> scanCode() async {
    _channel.invokeMethod<String>('scan');
  }

  /// 支付宝支付
  Future<void> aliPay() async {
    String orderInfo =
        "alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2015112600874818&biz_content=%7B%22out_trade_no%22%3A%222024052212832201482%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22TICKET202405221014402286822%22%2C%22total_amount%22%3A%222480.00%22%7D&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=https%3A%2F%2Ft-pay.hnair.com%2Fpaygateway%2Fpay%2FgatewayAliPayResultNotify%2Fv2%2Fsingle%2FHU%2F103&sign=sVsC0GYrwUiyN1ZGEEOE%2FZK98zZa8TRYPzyoKrOBzMWRDOFwKjRCFnaDW%2BUepc8DAWNeGoP5g6gFCrVSA5CutxWIG381kDGEY4uaNvyzTPffLMubj80eRPlyFXYjy91sni6kCk3urUK8X7NBm67PJ%2FkvlyEUUBGn7hJG%2Brdhuos%3D&sign_type=RSA&timestamp=2024-05-22+10%3A14%3A38&version=1.0";
    String result =
        (await _channel.invokeMethod<String>('aliPay', orderInfo)) ?? "";
    Map<String, dynamic> resultMap = jsonDecode(result);
    if (resultMap["resultStatus"] == "9000") {
      Fluttertoast.showToast(msg: "支付成功！");
    } else {
      Fluttertoast.showToast(msg: "支付失败！");
    }
    Navigator.push(
      contextRef,
      MaterialPageRoute(
          builder: (context) =>
              PaymentResult(isSuccess: resultMap["resultStatus"] == "9000")),
    );
  }

  /// 微信支付
  Future<void> wechatPay() async {
    //预支付订单信息
    String prepayId = "";
    String result =
        (await _channel.invokeMethod<String>('wechatPay', prepayId)) ?? "";
    //微信支付需要去服务端查询支付结果或者以服务端通知的结果为准，不建议直接以客户端的结果作为支付成功与否的结果
    Navigator.push(
      contextRef,
      MaterialPageRoute(builder: (context) => PaymentResult(isSuccess: true)),
    );
  }

  /// 分享
  Future<void> shareText() async {
    Map<String, String> params = <String, String>{};
    params.putIfAbsent("type", () => "text");
    params.putIfAbsent("text", () => "分享内容");
    _flutterShare.share(params);
  }

  ///跳转子页面
  void gotoSubWebPage(String openUrl) async {
    Navigator.push(
      contextRef,
      MaterialPageRoute(
          builder: (context) => SubWebPage(
                url: openUrl,
              )),
    );
  }

  ///打开应用市场
  Future<void> startAppGallery() async {
    String appId = "2015112600874818";
    _channel.invokeMethod<String>('startAppGallery', appId);
  }

  ///一键登录
  Future<void> quickLogin() async {
    _channel.invokeMethod<String>('HuaWeiQuickLogin');
  }

  Future<void> selectImages(dynamic arguments) async {
    String result =
        (await _channel.invokeMethod<String>('selectImages', arguments)) ??
            "xxx";
    List<dynamic> imageList = json.decode(result);
    setState(() {});
    //Fluttertoast.showToast(msg: "暂未实现！");
  }

  _saveLocalImage() async {
    //await Permission.photos.request();
    /*RenderRepaintBoundary boundary =
        _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundary.toImage();
    ByteData? byteData =
        await (image.toByteData(format: ui.ImageByteFormat.png));
    if (byteData != null) {
      final result =
          await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
      Fluttertoast.showToast(msg: result.toString());
    }*/
  }

  void _incrementCounter() async {
    await getPosition("11fff");
  }

  Future<void> requestPermission() async {
    /*final status = await permission.request();
    setState(() {
      _permissionStatus = status;
      print(_permissionStatus);
    });*/
  }
}
